# Setup pm2-logrotate for PPH Production (PowerShell)
# Usage: Run as Administrator in project root or from anywhere. Pure English to avoid codepage issues.

$ErrorActionPreference = 'Stop'

function Assert-Cmd([string]$cmd) {
  if (-not (Get-Command $cmd -ErrorAction SilentlyContinue)) {
    throw "Required command not found: $cmd"
  }
}

# Resolve project root (.. from scripts folder)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$ProjectRoot = Split-Path -Parent $ScriptDir
$Ecosystem = Join-Path $ProjectRoot 'config\ecosystem.config.cjs'

Write-Host "[PPH] ProjectRoot: $ProjectRoot" -ForegroundColor Cyan
Write-Host "[PPH] Ecosystem:   $Ecosystem" -ForegroundColor Cyan

# Check required commands
Assert-Cmd node
Assert-Cmd npm
Assert-Cmd npx

# Bind PM2_HOME locally to avoid conflicts with system-wide daemon
$pm2Home = Join-Path $ProjectRoot '.pm2'
$env:PM2_HOME = $pm2Home
Write-Host "[PPH] PM2_HOME = $pm2Home" -ForegroundColor Cyan

# Ensure PM2 daemon is clean
try { & npx pm2 kill | Out-Null } catch { Write-Warning "[PPH] pm2 kill failed or no daemon running." }

# Install pm2-logrotate (idempotent)
Write-Host "[PPH] Installing pm2-logrotate..." -ForegroundColor Yellow
& npx pm2 install pm2-logrotate

# Configure rotation policy (size + daily + compression)
Write-Host "[PPH] Configuring pm2-logrotate..." -ForegroundColor Yellow
& npx pm2 set pm2-logrotate:max_size 10M
& npx pm2 set pm2-logrotate:retain 7
& npx pm2 set pm2-logrotate:compress true
& npx pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
& npx pm2 set pm2-logrotate:rotateInterval 0 0 * * *
& npx pm2 set pm2-logrotate:workerInterval 30

# Show pm2 status and plugin config
Write-Host "[PPH] PM2 processes:" -ForegroundColor Green
& npx pm2 list
Write-Host "[PPH] pm2-logrotate current config:" -ForegroundColor Green
& npx pm2 conf pm2-logrotate

Write-Host "[PPH] Done. Logs will rotate at 10MB or daily with compression, keeping 7 days." -ForegroundColor Green

